/**
 * @file hoc.jsx.
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from "react";
import * as assign from 'object-assign';
import * as isPlainObject from 'lodash/isPlainObject';
import * as copy from 'copy-to-clipboard';
import * as cx from 'classnames';
import {filter} from '../util';
import TooltipWrapper from '../../widgets/tooltip';

const returnFalse = () => false;

export const Enhance = ComposedComponent => class Copyable extends PureComponent {
  static propTypes = {
    copyable: PropTypes.any,
    onNotify: PropTypes.func
  };

  constructor(props) {
    super(props);

    this.copy = this.copy.bind(this);
    let copyable = props.copyable;
    this.state = {
      copyable: copyable ? assign({
        label: '',
        icon: 'fa fa-clipboard',
        className: 'btn-link btn-sm',
        tooltip: '点击复制',
        text: null,
        hideRaw: false
      }, isPlainObject(copyable) ? copyable : null) : null
    };
  }

  componentWillReceiveProps(nextProps) {
    const props = this.props;

    if (props.copyable !== nextProps.copyable) {
      let copyable = nextProps.copyable;

      this.setState({
        copyable: copyable ? assign({
          label: '',
          icon: 'fa fa-clipboard',
          className: 'btn-link btn-sm',
          tooltip: '点击复制',
          text: null,
          hideRaw: false
        }, isPlainObject(copyable) ? copyable : null) : null
      });
    }
  }

  copy() {
    const {
      value,
      onNotify,
      data
    } = this.props;

    const copyable = this.state.copyable;
    const text = copyable.text ? filter(copyable.text, data) : value;

    if (copy(text) && onNotify) {
      onNotify({
        level: 'success',
        title: '拷贝成功',
        message: '内容已拷贝到剪切板'
      });
    }
  }


  render() {
    const additional = {};
    const copyable = this.state.copyable;
    const value = this.props.value;

    if (copyable) {
      if (copyable.hideRaw) {
        additional.body = '';
      }

      additional.affix = (
        <a className={cx('btn', copyable.className, value ? '' : 'disabled')} onClick={this.copy}>
          {copyable.label || ''}
          {copyable.icon ? (<i className={copyable.icon} />) : null}
        </a>
      );

      if (copyable.tooltip) {
        additional.affix = (
          <TooltipWrapper id={this.props.$path} tooltip={copyable.tooltip} placement={copyable.tooltipPlacement || 'top'}>
            {additional.affix}
          </TooltipWrapper>
        );
      }
    }

    return (
      <ComposedComponent
        {...this.props}
        {...additional}
      />
    )
  }
};

export default Enhance;